package com.sgu6.sgu6_machine.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sgu6.sgu6_machine.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ControlAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {

    List<String> controlName;
    @BindView(R.id.tvControlName)
    TextView tvControlName;
    private int prePosition = 0;

    public ControlAdapter(List<String> controlName) {
        this.controlName = controlName;
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_control, viewGroup, false);
        v.setOnClickListener(this);
        return new Holder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        viewHolder.itemView.setTag(i);

        if (viewHolder instanceof Holder) {
            ((Holder) viewHolder).tvControlName.setText(controlName.get(i));
            if (prePosition == i){
                ((Holder) viewHolder).tvIndicate.setVisibility(View.VISIBLE);
            }else{
                ((Holder) viewHolder).tvIndicate.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public int getItemCount() {
        return controlName.size();
    }

    @Override
    public void onClick(View v) {
        int position = (int) v.getTag();
        prePosition = position;
        notifyDataSetChanged();
        listener.onItemClick(position);
    }


    static class Holder extends RecyclerView.ViewHolder {
        @BindView(R.id.tvControlName)
        TextView tvControlName;
        @BindView(R.id.tvIndicate)
        TextView tvIndicate;

        Holder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    public interface OnItemControlClickListener{
        void onItemClick(int position);
    }
    private OnItemControlClickListener listener;
    public void setOnClickListener(OnItemControlClickListener listener){
        this.listener = listener;
    }
}
